package top.z.template.parse.ast;

import top.z.template.Context;
import top.z.template.Template;
import top.z.template.parse.Ast.Expression;
import top.z.template.parse.Ast.Node;
import top.z.template.parse.Span;

import java.io.IOException;
import java.io.OutputStream;

/**
 * Return
 */
public class Return extends Node {

    public static final ReturnValue RETURN_SENTINEL = new ReturnValue();
    private final       Expression  returnValue;

    public static class ReturnValue {

        private final ThreadLocal<Object> value = new ThreadLocal<>();

        public Object getValue() {
            return value.get();
        }

        public void setValue(Object value) {
            this.value.set(value);
        }
    }

    public Return(Span span, Expression returnValue) {
        super(span);
        this.returnValue = returnValue;
    }

    public Expression getReturnValue() {
        return returnValue;
    }

    @Override
    public Object evaluate(Template template, Context context, OutputStream out) throws IOException {
        RETURN_SENTINEL.setValue(returnValue != null ? returnValue.evaluate(template, context, out) : null);
        return RETURN_SENTINEL;
    }

}
